package com.yueyang.sojourn.server.service.share;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yueyang.sojourn.server.common.baymax.web.result.JAssert;
import com.yueyang.sojourn.server.model.po.Share;
import com.yueyang.sojourn.server.model.po.SojournMerch;
import com.yueyang.sojourn.server.model.po.SojournOrder;
import com.yueyang.sojourn.server.model.vo.ShareVo;
import com.yueyang.sojourn.server.model.vo.SojournOrderVo;
import com.yueyang.sojourn.server.model.vo.UploadResult;
import com.yueyang.sojourn.server.service.sojourn.merch.SojournMerchService;
import com.yueyang.sojourn.server.service.sojourn.order.SojournOrderService;
import com.yueyang.sojourn.server.service.wx.WxServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.stream.Collectors;

/**
 * 分销service
 * @author Stepehn.Shi
 * @since 2020/05/02
 */
@Service
public class ShareService {
    @Autowired
    private ShareMapper shareMapper;
    @Autowired
    private SojournMerchService merchService;
    @Autowired
    private WxServer wxServer;
    @Autowired
    private SojournOrderService orderService;

    public Share findByUserIdAndMerchId(Long userId, Long merchId) {
        return this.shareMapper.findByUserIdAndMerchId(userId, merchId);
    }

    public void insert(Share share) {
        this.shareMapper.insert(share);
    }

    public void update(Share share) {
        this.shareMapper.updateByPrimaryKey(share);
    }

    /**
     * 创建分销
     * @param userId
     * @param merchId
     * @return
     */
    private Share create(Long userId, Long merchId) {
        SojournMerch merch = merchService.selectByPrimaryKey(merchId);
        JAssert.pass(merch != null, "商品不存在,id=" + merchId);
        Share share = new Share();
        share.setMerchId(merchId);
        share.setUserId(userId);
        share.setShareImg("");
        share.setCtime(new Date());
        share.setState(1);
        this.shareMapper.insert(share);
        // 生成小程序码 并更新
        String params = String.format("%s_%s", merchId, share.getId());
        UploadResult uploadResult = this.wxServer.getAcode(userId, "pages/detail/detail", 280L,  params);
        share.setShareImg(uploadResult.getKey());
        this.update(share);
        return share;
    }

    /**
     * 分销
     * @param merchId
     * @param loginUserId
     * @return
     */
    public Share share(Long merchId, Long loginUserId) {
        Share share = this.findByUserIdAndMerchId(loginUserId, merchId);
        if (share == null) {
            share = create(loginUserId, merchId);
        }
        return share;
    }

    /**
     * 查询用户的分销列表
     * @param loginUserId
     * @param pageNum
     * @param pageSize
     * @return
     */
    public PageInfo<ShareVo> findUserShareList(Long loginUserId, Integer pageNum, Integer pageSize) {
        PageInfo<ShareVo> pageInfo = PageHelper.startPage(pageNum, pageSize)
                .doSelectPageInfo(() -> this.shareMapper.findUserShareList(loginUserId));

        return pageInfo;
    }

    /**
     * 获取分销订单列表
     * @param loginUserId
     * @param pageNum
     * @param pageSize
     * @return
     */
    public PageInfo<SojournOrderVo> findMyShareOrderList(Long loginUserId, Integer pageNum, Integer pageSize) {
        PageInfo<SojournOrder> pageInfo = orderService.findMyShareOrderList(loginUserId, pageNum, pageSize);
        PageInfo<SojournOrderVo> page = new PageInfo<>();
        BeanUtils.copyProperties(pageInfo, page);
        page.setList(pageInfo.getList().stream()
                .map(po -> {
                    SojournOrderVo vo = new SojournOrderVo();
                    BeanUtils.copyProperties(po, vo);
                    vo.setMerchSales(JSON.parseArray(po.getMerchSale(), Integer.class));
                    Long now = System.currentTimeMillis();
                    Long remainTime = now > po.getPayEndTime().getTime() ? 0 : (po.getPayEndTime().getTime() - now) / 1000;
                    vo.setPayRemainTime(remainTime);
                    return vo;
                })
                .collect(Collectors.toList()));
        return page;
    }

    public void visitIncrease(Long id) {
        this.shareMapper.visitIncrease(id);
    }

    public void registIncrease(Long id) {
        this.shareMapper.registIncrease(id);
    }

    public void orderIncrease(Long id) {
        this.shareMapper.orderIncrease(id);
    }

    void dealIncrease(Long id) {
        this.shareMapper.dealIncrease(id);
    }
}
